<?php
namespace App\Components\Twig;

use Psr\Http\Message\ServerRequestInterface;
use RuntimeException;
use Twig\Environment;
use Twig\Extension\ExtensionInterface;
use Twig\Loader\FilesystemLoader;
use Twig\Loader\LoaderInterface;
use Twig\RuntimeLoader\RuntimeLoaderInterface;

class Twig
{
    protected $loader;

    protected $environment;

    public function __construct(LoaderInterface $loader, array $settings = [])
    {
        $this->loader = $loader;
        $this->environment = new Environment($this->loader, $settings);
        $extension = new TwigExtension();
        $this->addExtension($extension);
    }

    public function addExtension(ExtensionInterface $extension): void
    {
        $this->environment->addExtension($extension);
    }

    public function addRuntimeLoader(RuntimeLoaderInterface $runtimeLoader): void
    {
        $this->environment->addRuntimeLoader($runtimeLoader);
    }

    public static function create(string $path, array $settings = []): self
    {
        $loader = new FilesystemLoader();

        $loader->addPath($path);

        return new self($loader, $settings);
    }

    public static function fromRequest(ServerRequestInterface $request, string $attributeName = 'view'): self
    {
        $twig = $request->getAttribute($attributeName);
        if (!($twig instanceof self)) {
            throw new RuntimeException('Twig could not be found in the server request attributes using the key: ' . $attributeName);
        }
        return $twig;
    }

    public function fetch(string $template, array $data = []): string
    {
        $displayContext = $this->environment->render($template, $data);
        if ($this->environment->isDebug() === false) {
            $displayContext = str_replace("\t", '', $displayContext);
            $displayContext = str_replace(str_repeat(' ', 4), '', $displayContext);
            $displayContext = str_replace(PHP_EOL, '', $displayContext);
        }
        return $displayContext;
    }
}
